import cv2
import dlib
import numpy as np
from matplotlib.path import Path


def shape_to_np(shape, dtype='int'):
    coords = np.zeros((68, 2), dtype=dtype)
    for i in range(0, 68):
        coords[i] = (shape.part(i).x, shape.part(i).y)
    return coords


def FR(file, predictor):
    """
    可进行图片人脸识别
    :param file: 图片文件名
    :param predictor: 提前加载好的的AI模型
    :return:
    """
    # get file path
    img = cv2.imread('../data/TMP/%s' % file)
    # conver to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    detector = dlib.get_frontal_face_detector()

    # rects contains all the faces detected
    rects = detector(gray, 1)
    shape = predictor(gray, rects[0])
    shape = shape_to_np(shape)

    for point in shape:
        cv2.circle(img, point, 1, (0, 0, 255), -1)

    cv2.imshow('a', img)
    cv2.waitKey(0)
    return 0


if __name__ == '__main__':
    model = dlib.shape_predictor('../models/shape_predictor_68_face_landmarks.dat')     # 模型加载
    FR('5.png', model)
